package rds

import (
	"context"
	"fmt"
	"github.com/redis/go-redis/v9"
)

func Client(addr string, password string) *redis.Client {
	return redis.NewClient(&redis.Options{
		Addr:     addr,
		Password: password,
	})
}

func Conn(ctx context.Context, client *redis.Client) (conn *redis.Conn, err error) {
	var resp string
	conn = client.Conn()
	resp, err = conn.Ping(ctx).Result()
	if err != nil {
		return nil, err
	} else if resp != "PONG" {
		return nil, fmt.Errorf("redis tcp 127.0.0.1:6379 connect failed")
	}
	return conn, nil
}

func LoadScripts(ctx context.Context, client *redis.Client, scripts map[string]string) (hashs map[string]string, err error) {
	hashs = make(map[string]string, len(scripts))

	for k, script := range scripts {
		var hash string
		script := redis.NewScript(script)
		hash, err = script.Load(ctx, client).Result()
		if err != nil {
			return nil, err
		}
		hashs[k] = hash
	}
	return
}
